from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from sensors.models import DevInfo
import time
import datetime


def closeSensor(name):
    from sensors.models import SystemSitting
    manualStatus = SystemSitting.objects.get(type_name='manual').status
    if not manualStatus:
        import time
        targetDev = DevInfo.objects.get(dev_name=name)
        localtime = time.asctime(time.localtime(time.time()))
        """关闭传感器"""
        channel_layer = get_channel_layer()

        async_to_sync(channel_layer.group_send)("sensors", {
            "type": "events",
            "message": {
                'type': 'status',
                'msg': '已关闭'
            }
        })
        print("close!" + localtime + '--' + name)
        targetDev.status = 'close'
        targetDev.save()


def openSensor(name):
    from sensors.models import SystemSitting
    manualStatus = SystemSitting.objects.get(type_name='manual').status
    if not manualStatus:
        import time
        targetDev = DevInfo.objects.get(dev_name=name)
        localtime = time.asctime(time.localtime(time.time()))
        """开启传感器"""
        channel_layer = get_channel_layer()

        async_to_sync(channel_layer.group_send)("sensors", {
            "type": "events",
            "message": {
                'type': 'status',
                'msg': '已开启'
            }
        })
        print("open!" + localtime + '--' + name)
        targetDev.status = 'open'
        targetDev.save()


# TODO 屏蔽自动底层
'''
def closeSensor(name):
    import time
    targetDev = DevInfo.objects.get(dev_name=name)
    localtime = time.asctime(time.localtime(time.time()))
    """关闭传感器"""
    channel_layer = get_channel_layer()
    if tcp.tcpSwitchClose(name):
        async_to_sync(channel_layer.group_send)("sensors", {
            "type": "events",
            "message": {
                'type': 'status',
                'msg': '已关闭'
            }
        })
        print("close!" + localtime + '--' + name)
        targetDev.status = 'close'
        targetDev.save()
    else:
        if tcp.tcpSwitchClose(name):
            async_to_sync(channel_layer.group_send)("sensors", {
                "type": "events",
                "message": {
                    'type': 'status',
                    'msg': '出现错误，未正常关闭设备'
                }
            })
            print("close err!" + localtime + '--' + name)
            targetDev.status = 'open'
            targetDev.save()


def openSensor(name):
    import time
    targetDev = DevInfo.objects.get(dev_name=name)
    localtime = time.asctime(time.localtime(time.time()))
    """开启传感器"""
    channel_layer = get_channel_layer()
    if tcp.tcpSwitchOpen(name):
        async_to_sync(channel_layer.group_send)("sensors", {
            "type": "events",
            "message": {
                'type': 'status',
                'msg': '已开启'
            }
        })
        print("open!" + localtime + '--' + name)
        targetDev.status = 'open'
        targetDev.save()
    else:
        async_to_sync(channel_layer.group_send)("sensors", {
            "type": "events",
            "message": {
                'type': 'status',
                'msg': '出现错误，未正常开启设备'
            }
        })
        print("open err!" + localtime + '--' + name)
        targetDev.status = 'close'
        targetDev.save()
'''


def resetSensorState(name, times):
    targetDev = DevInfo.objects.get(dev_name=name)
    now = int(time.time())  # 当前时间戳
    now_date = datetime.datetime.now().strftime('%Y-%m-%d')  # 当日时间
    tmp_arr = []
    for i in times:
        startTime_arr = time.strptime(now_date + ' ' + i[0], "%Y-%m-%d %H:%M:%S")
        endTime_arr = time.strptime(now_date + ' ' + i[1], "%Y-%m-%d %H:%M:%S")
        startTime = int(time.mktime(startTime_arr))
        endTime = int(time.mktime(endTime_arr))
        if startTime <= now < endTime:
            tmp_arr.append(True)
        else:
            tmp_arr.append(False)
    if True in tmp_arr:
        # TODO 打开设备
        targetDev.status = 'open'
        targetDev.save()
    else:
        # TODO 关闭设备
        targetDev.status = 'close'
        targetDev.save()


def resetAllSensorsState():
    targetDev = DevInfo.objects.all()
    for i in targetDev:
        if not i.other_set and i.auto_times:
            newTimes = []
            new_item = i.auto_times.split(';')
            for j in new_item:
                newTimes.append(j.split('-'))
            resetSensorState(i.dev_name, newTimes)
    print('设备状态校对')


# 打开关闭风扇
def toggleFan(i):
    from sensors.models import SystemSitting
    manualStatus = SystemSitting.objects.get(type_name='manual').status
    if not manualStatus:
        channel_layer = get_channel_layer()
        targetDev = DevInfo.objects.get(dev_name='排风扇')
        if i:
            async_to_sync(channel_layer.group_send)("sensors", {
                "type": "events",
                "message": {
                    'type': 'status',
                    'msg': '温度超出设定值，已自动开启风扇'
                }
            })
            # TODO 打开风扇
            targetDev.status = 'open'
        else:
            async_to_sync(channel_layer.group_send)("sensors", {
                "type": "events",
                "message": {
                    'type': 'status',
                    'msg': '风扇自动关闭'
                }
            })
            # TODO 关闭风扇
            targetDev.status = 'close'
        targetDev.save()


# 范围超过风扇的阈值进行的函数
def setAutoForFan():
    # 获取数据库中风扇开启的时间设定
    targetDev = DevInfo.objects.get(dev_name='排风扇')
    interval = float(targetDev.auto_times)
    # 导入定时组件
    from sensors.common.Scheduler import scheduler
    # 删除风扇定时任务
    try:
        scheduler.remove_job('fan_close')
    except:
        pass
    finally:
        # 指定关闭的时间
        closeTime = (datetime.datetime.now() + datetime.timedelta(minutes=interval)).strftime("%Y-%m-%d %H:%M:%S")
        # 执行开启风扇
        toggleFan(True)
        # 添加风扇关闭任务
        scheduler.add_job(toggleFan, 'date', run_date=closeTime, args=[False], id="fan_close")


# 蠕动泵开关
def toggleRu(status):
    from sensors.models import SystemSitting
    manualStatus = SystemSitting.objects.get(type_name='manual').status
    if not manualStatus:
        channel_layer = get_channel_layer()
        targetDev = DevInfo.objects.get(dev_name='蠕动泵')
        if status:
            async_to_sync(channel_layer.group_send)("sensors", {
                "type": "events",
                "message": {
                    'type': 'status',
                    'msg': '已自动开启蠕动泵'
                }
            })
            # TODO 打开泵
            targetDev.status = 'open'
            print(datetime.datetime.now())
            print('开启')
        else:
            async_to_sync(channel_layer.group_send)("sensors", {
                "type": "events",
                "message": {
                    'type': 'status',
                    'msg': '已自动关闭蠕动泵'
                }
            })
            # TODO 关闭泵
            targetDev.status = 'close'
            print(datetime.datetime.now())
            print('关闭')
        targetDev.save()


# 范围超出设定值后开启蠕动泵
def setAutoForSquirm():
    # 获取数据库中风扇开启的时间设定
    targetDev = DevInfo.objects.get(dev_name='蠕动泵')
    interval = float(targetDev.auto_times)
    # 导入定时组件
    from sensors.common.Scheduler import scheduler
    # 添加蠕动泵打开任务
    scheduler.add_job(toggleRu,
                      'interval',
                      minutes=interval * 2,
                      args=[True],
                      id='ru_open',
                      next_run_time=datetime.datetime.now())
    # 添加蠕动泵关闭任务
    startTime = (datetime.datetime.now() + datetime.timedelta(minutes=interval)).strftime("%Y-%m-%d %H:%M:%S")
    scheduler.add_job(toggleRu,
                      'interval',
                      minutes=interval * 2,
                      args=[False],
                      id='ru_close',
                      next_run_time=startTime)


# 回到范围内停止蠕动泵的定时
def closeAutoForSquirm():
    from sensors.common.Scheduler import scheduler
    channel_layer = get_channel_layer()
    targetDev = DevInfo.objects.get(dev_name='蠕动泵')
    try:
        scheduler.remove_job('ru_open')
        scheduler.remove_job('ru_close')
    except:
        pass

    # 执行关闭
    async_to_sync(channel_layer.group_send)("sensors", {
        "type": "events",
        "message": {
            'type': 'status',
            'msg': '已自动关闭蠕动泵'
        }
    })
    targetDev.status = 'close'
    targetDev.save()
